﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LightCAD.Three
{
    public class WebGLAnimation
    {
        private IGraphicsContext context = null;
        private bool isAnimating = false;
        private Action<double, object> animationLoop = null;
        private object requestId = null;
        private static double origin = JsDate.now();
        private void onAnimationFrame(double time, object frame)
        {
            if (isAnimating == false) return;
            time = JsDate.now() - origin;
            animationLoop(time, frame);
            //requestId = context.requestAnimationFrame(onAnimationFrame);

        }
        private void onAnimationFrameHandle(object sender, FrameEventArgs e)
        {
            onAnimationFrame(e.Time, null);
        }
        public void start()
        {
            if (isAnimating) return;
            if (animationLoop == null) return;
            //requestId = context.requestAnimationFrame(onAnimationFrame);
            context.RenderFrame += onAnimationFrameHandle;
            isAnimating = true;
        }

        public void stop()
        {
            if (context != null)
            {
                context.RenderFrame -= onAnimationFrameHandle;
            }
            //context.cancelAnimationFrame(requestId);
            isAnimating = false;
        }


        public void setAnimationLoop(Action<double, object> onAnimationFrame)
        {
            animationLoop = onAnimationFrame;
        }


        public void setContext(IGraphicsContext value)
        {
            context = value;
        }
    }
}
